package com.fxhy.controller;


import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baby.myutils.StringUtils;
import com.fxhy.base.JBaseController;
import com.fxhy.bean.AgentUser;
import com.fxhy.contants.Constants;
import com.fxhy.service.UserService;
import com.fxhy.service.AgentLogService;
import com.fxhy.utils.Base64Util;
import com.fxhy.utils.DateUtils;
import com.fxhy.utils.JWTUtil;
import com.fxhy.vo.ResponseBodyEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@Api(value="登录接口")
@Slf4j
public class Login extends JBaseController{
	
	@Autowired
	private UserService userService;
	
	@Autowired 
	private AgentLogService AgentLogService;
	
	@ApiOperation("测试接口")
	@RequestMapping("test")
    public Object test(@RequestBody(required = false) ModelMap modelMap) {
        return setSuccessModelMap(modelMap,"Hello World");
    }
	
	
	@ApiOperation("登录验证图形验证码")
	public ResponseBodyEntity virifyCode (String vrifyCode,String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		if (!JWTUtil.verify(token, vrifyCode, Constants.KAPTCHA_KEY)) { 
			log.error("用户登录,图形验证码已过期");
			responseBodyEntity.setMsg("图形验证码已过期!");
			responseBodyEntity.setState(Constants.FAILURE);
		}else{
			responseBodyEntity.setData("");
			responseBodyEntity.setMsg("图形验证码正确!");
			responseBodyEntity.setState(Constants.SUCCEED);
		}
		return responseBodyEntity;
	}
	
	/**
	 * 描述: 登录
	 * 返回值:UserInfo
	 * @throws Exception 
	 */
	@ApiOperation("登录   没有就自动注册")
	@RequestMapping(value = "login",method = RequestMethod.POST)
	public ResponseBodyEntity login(String phoneNum,String securityCode,String device,String virifyCode,String token,HttpServletRequest request) throws Exception{
		log.info("用户登录,手机号:{},短信验证码:{}",phoneNum,securityCode);
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		String ip = getIP(request);
		if(ip == null || ip.equals("")){
			log.error("屏蔽IP，不允许登录!");
			responseBodyEntity.setMsg("屏蔽IP，不允许登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		
		if(phoneNum != null && !phoneNum.equals("")){
			AgentUser userInfo = userService.findUserByPhone(phoneNum);
			if(userInfo != null && userInfo.getUserId() != null) {
				if(userInfo.getStatus() == 1){
					if(userInfo.getSecurityCode() != null && !userInfo.getSecurityCode().equals("") && userInfo.getSecurityCode().equals(securityCode)){
						//权限等级大于10说明才是管理员
						if(userInfo.getMemberType() == 1){
							userInfo.setLastLoginTime(DateUtils.getNowDate());
							userInfo.setUpdateTime(DateUtils.getNowDate());
//							userInfo.setSecurityCode("");
							userInfo.setIsOnline(1);
							userInfo = userService.updateUser(userInfo);
							
							//登录日志
							AgentLogService.saveAgentLog(userInfo,1,ip);
							
							String newToken = JWTUtil.sign(userInfo.getUserId()+"",userInfo.getLastLoginTime());
							userInfo.setHeadImgUrl("data:image/jpeg;base64," + Base64Util.GetBaseStrByImg(userInfo.getHeadImgUrl()));
							responseBodyEntity.setData(userInfo);
							responseBodyEntity.setMsg("登录成功");
							responseBodyEntity.setState(Constants.SUCCEED);
							responseBodyEntity.setToken(newToken);
						}else{
							responseBodyEntity.setData(userInfo);
							responseBodyEntity.setMsg("你没有权限登陆此系统!");
							responseBodyEntity.setState(Constants.FAILURE);
							responseBodyEntity.setToken("");
						}
					}else{
						responseBodyEntity.setMsg("短信验证码错误!");
						responseBodyEntity.setState(Constants.FAILURE);
					}
				}else if(userInfo.getStatus() == 0){
					responseBodyEntity.setMsg("你的账号处在冻结期!解冻请联系生产商进行申诉!");
					responseBodyEntity.setState(Constants.FAILURE);
				}else if(userInfo.getStatus() == -1){
					responseBodyEntity.setMsg("账号已处在黑名单! 请遵守规定!");
					responseBodyEntity.setState(Constants.FAILURE);
				}else{
					responseBodyEntity.setMsg("无效账号! 无法登录!");
					responseBodyEntity.setState(Constants.FAILURE);
				}
			}else {
				responseBodyEntity.setMsg("手机号错误!");
				responseBodyEntity.setState(Constants.FAILURE);
			}
		}else{
			responseBodyEntity.setMsg("手机号不能为空!");
			responseBodyEntity.setState(Constants.FAILURE);
		}
		return responseBodyEntity;
	}
	
	/**
	 * 获取IP
	 * @param request
	 * @return 
	 * @throws Exception
	 */
	public String getIP(HttpServletRequest request) throws Exception{
		if (request == null) {
			throw (new Exception("获取IP失败!请不要做IP处理!"));
		}
		String ipString = request.getHeader("x-forwarded-for");
		if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
			ipString = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
			ipString = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
			ipString = request.getRemoteAddr();
		}
		// 多个路由时，取第一个非unknown的ip
		final String[] arr = ipString.split(",");
		for (final String str : arr) {
			if (!"unknown".equalsIgnoreCase(str)) {
				ipString = str;
				break;
			}
		}
		return ipString;
	}
}
